#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    isLoadFinished = true;

    //  Toolbar
    tbtnBack = new QToolButton(this);
    tbtnBack->setText(tr("Back"));
    connect(tbtnBack, SIGNAL(clicked()), this, SLOT(onTbtnBackClicked()));
    tbtnGo = new QToolButton(this);
    tbtnGo->setText(tr("Go"));
    connect(tbtnGo, SIGNAL(clicked()), this, SLOT(onTbtnGoClicked()));

    lineAddress = new QLineEdit("http://", this);

    ui->toolBar->addWidget(tbtnBack);
    ui->toolBar->addWidget(lineAddress);
    ui->toolBar->addWidget(tbtnGo);

    //  Shortcuts
    QShortcut *shortcutGo = new QShortcut(QKeySequence(QKeySequence::InsertParagraphSeparator), this);
    connect(shortcutGo, SIGNAL(activated()), this, SLOT(onTbtnGoClicked()));

    connect(ui->webView, SIGNAL(loadFinished(bool)), this, SLOT(onPageLoadFinished(bool)));
    connect(ui->webView, SIGNAL(linkClicked(QUrl)), this, SLOT(onLinkClicked(QUrl)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::onTbtnBackClicked()
{
    ui->webView->stop();
    ui->webView->back();
}

void MainWindow::onTbtnGoClicked()
{
    QString url = lineAddress->text();
    if(url.left(7) != "http://")
        url = "http://" + url;

    ui->webView->load(QUrl(url));
}

void MainWindow::onPageLoadFinished(bool success)
{
    if(success)
        lineAddress->setText(ui->webView->url().toString());

    ui->statusBar->showMessage(tr("Finished"), 2000);

    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(ui->webView->page(), SIGNAL(linkHovered(QString,QString,QString)), this, SLOT(onLinkHovered(QString,QString,QString)));
}

void MainWindow::onLinkClicked(const QUrl &url)
{
    bool isValid = LinkChecker::check(url, ui->webView->url());

    if(!isValid)
    {
        QMessageBox msgbox(QMessageBox::Warning, tr("Warning"),
                           tr("<b>You may encountered a fake link!</b><br />Are you sure where you will go?"),
                           QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
        msgbox.setTextFormat(Qt::RichText);
        msgbox.setDetailedText(tr("Link URL:\n") + url.toString());
        int rslt = msgbox.exec();

        if(QMessageBox::No == rslt || QMessageBox::Cancel == rslt)
            return ;
    }

    ui->webView->load(url);    
}

void MainWindow::onLinkHovered(const QString &link, const QString &title, const QString &textContent)
{
    if(link.isEmpty())
        ui->statusBar->clearMessage();
    else
        ui->statusBar->showMessage(link);
}
